/**
 * 
 */
package com.lazyshopkeeper.front.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lazyshopkeeper.front.apiService.IItemCatsService;
import com.lazyshopkeeper.front.persistence.CatelogMapper;
import com.lazyshopkeeper.front.service.ICatelogService;
import com.taobao.api.ApiException;
import com.taobao.api.domain.ItemCat;

/**
 * @author xuyuqi
 *
 */
@Service
public class CatelogService implements ICatelogService {

	@Autowired
	private IItemCatsService itemCatsService;
	@Autowired
	private CatelogMapper catelogMapper;
	
	/* (non-Javadoc)
	 * @see com.lazyshopkeeper.front.service.ICatelogService#synchronismCatelog()
	 */
	@Override
	public boolean synchronismCatelog() {
		new CatelogSynchronismThread().start();
		return false;
	}
	
	private class CatelogSynchronismThread extends Thread{
		
		public void run(){
			try {
				getAndSynchronismChildren(0l);
			} catch (ApiException e) {
				e.printStackTrace();
			}
		}
		
		public void getAndSynchronismChildren(long parentId) throws ApiException{
			
			List<ItemCat> icList = itemCatsService.getChildCatelogs(parentId);
			for (ItemCat ic : icList) {
				if(ic.getIsParent()){
					getAndSynchronismChildren(ic.getCid());
				}
				
				if(catelogMapper.getCatelog(ic.getCid()) != null){
					catelogMapper.updateCatelog(ic);
				} else {
					catelogMapper.addCatelog(ic);
				}
			}
			
		}
	}

}
